package com.xykj.threadStation;

import java.util.Random;
import java.util.concurrent.CountDownLatch;

public class ThreadTiming {
	private int nThread;

    private CountDownLatch startGate;
    private CountDownLatch endGate;

    public ThreadTiming(int nThread, CountDownLatch startGate, CountDownLatch endGate) {

        this.nThread = nThread;
        this.startGate = startGate;
        this.endGate = endGate;
    }

    
    // 为了保持票数的一致，票数要静态
    static int tick = 10;
     
    // 创建一个静态钥匙
    
    class Station implements Runnable{
    	
        // 重写run方法，实现买票操作
        @Override
        public void run() {
        	try {
        		while(tick > 0){
        			startGate.await();
                    Random random = new Random();
                    int num = random.nextInt(500) + 500;
                    if (tick > 0) {
                        System.out.println(Thread.currentThread().getName()  + "卖出了第" + tick + "张票");
                        tick--;
                    } else {
                       
                    }
        			Thread.sleep(num);
        		}
            } catch (InterruptedException e) {
                e.printStackTrace();
            }finally {
                endGate.countDown();
            }
        }
    }
        

    public long timeTasks() {
        for(int i = 0; i < nThread; i++){
            Thread thread = new Thread(new Station());
            thread.start();
        }

        long start = System.currentTimeMillis();
        //所有阻塞的任务同时开始
        startGate.countDown();
        try {
            //主线程阻塞,等待其他所有 worker 线程完成后再执行
            endGate.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        long end = System.currentTimeMillis();
        System.out.println("票卖完了,用时: " + (end - start)/1000 + "s");

        return end - start;
    }

    public static void main(String[] args) {
        int nThread = 3;
        CountDownLatch startGate = new CountDownLatch(1);
        CountDownLatch endGate = new CountDownLatch(nThread);

        new ThreadTiming(nThread, startGate, endGate).timeTasks();

    }

}
    
